import { PropsWithChildren } from 'react';
import { useEffect, FC, useState } from 'react';
import { View, Text, Button, Image } from '@tarojs/components'
import { AtButton, AtToast } from 'taro-ui'
import './index.less'
import Taro from '@tarojs/taro';
import { useDispatch, useSelector } from 'react-redux';
import { getLogin, phoneLogin } from '@api/login.ts'
import Uncheck from '@resource/tabImg/uncheck.png'
import Checked from '@resource/tabImg/checked.png'



const Index: FC<PropsWithChildren> = () => {
  // dispatch({ type: 'count/add', payload: 1 });
  const dispatch = useDispatch();
  const { count } = useSelector((store: any) => {
    return store.counter;
  });
  const [checked, setChecked] = useState(false);
  const [show, setShow] = useState(false)
  const [loading, setLoadng] = useState(false)
  useEffect(() => {
    // 任何你需要在组件挂载时执行的副作用
    // const userInfo = Taro.getStorageSync('userInfo');
    // if (userInfo) {
    //   Taro.switchTab({ url: '/pages/index/index' });
    // }
  }, []);

  const goTologin = () => {
    Taro.navigateTo({
      url: '/pages/admin/index',
    })
  }

  const getUserInfo = () => {
    wx.getUserInfo({
      success: (infoRes) => {
        const userInfo = infoRes.userInfo;
        Taro.setStorageSync('userInfo', userInfo);
      },
      fail: () => {
        // Taro.showToast({ title: '登录失败', icon: 'none' });
      }
    });
  }

  const goToLogin = (phoneCode) => {
    setLoadng(true)
    wx.login({
      success: async (loginRes) => {
        if (loginRes.code) {
          try {
            getUserInfo()
            const loginData = await getLogin({ code: loginRes.code });
            if (loginData.code === 200 && loginData.data) {
              const { open_id } = loginData.data;
              Taro.setStorageSync('loginInfo', loginData.data);
              if (phoneCode) {
                const result = await phoneLogin({ phone_code: phoneCode, open_id });
                if (result.code === 200 && result.data) {
                  const { token } = result.data
                  Taro.setStorageSync('token', token);
                  Taro.setStorageSync('verification_pass', true);
                  Taro.showToast({ title: '登录成功', icon: 'success' });
                  Taro.switchTab({ url: '/pages/index/index' });
                } else {
                  Taro.showToast({ title: '登录失败', icon: 'none' });
                }
              }
            } else {
              Taro.showToast({ title: '登录失败', icon: 'none' });
            }
          } catch (error) {
            console.log('error', error)
            Taro.showToast({ title: '登陆失败', icon: 'none' });
          }
        } else {
          Taro.showToast({ title: '登录失败', icon: 'none' });
        }
        setLoadng(false)
      }
    });
  }

  const gotoPreview = (type: string) => {
    const user_pro = `/pages/userProtocol/index?previwew_type=${type}`
    const privacy_pro = `/pages/privacyProtocol/index?previwew_type=${type}`

    Taro.navigateTo({
      url: type === 'userProtocol' ? user_pro : privacy_pro
    });
  }

  const getPhoneNumber = (e) => {
    const { code } = e.detail;
    if (code == undefined) {
      Taro.showModal({
        title: '提示',
        content: '需要通过授权才能继续，请重新点击并授权',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            // console.log('用户点击确定')
          } else if (res.cancel) {
            // console.log('用户点击取消')
          }
        }
      })
      return
    }
    goToLogin(code)
  };

  return (
    <View className="login">
      <View className='body'>
        <View className='top'>
          {/* <Image className='loginImg' src={LoginBg} mode='aspectFill' /> */}
        </View>
        <View className='bottom'>
          <AtButton className='usePhonenumber' onClick={goTologin}>手机号安全登陆</AtButton>
          {
            checked &&
            <AtButton className='oneClickLogin'
              openType="getPhoneNumber"
              onGetPhoneNumber={getPhoneNumber}
              loading={loading}
            >
              一键登录
          </AtButton>}
          {!checked &&
            <AtButton className='oneClickLogin'
              onClick={() => setShow(true)}
              loading={loading}
            >
              一键登录
          </AtButton>
          }
        </View>
      </View>
      <View className='footer'>
        <View className='desc'>
          <View className='cicrle' onClick={() => setChecked(!checked)} >
            {
              !checked ? <Image className='checkbox' src={Uncheck} mode='aspectFill' /> : <Image className='checkbox' src={Checked} mode='aspectFill' />
            }
          </View>
          <Text>
            我已经阅读同意
            <Text className='protocol' onClick={() => gotoPreview('userProtocol')}>《搞薯条用户协议》</Text>
            ，
          <Text className='protocol' onClick={() => gotoPreview('privacyProtocol')}>《隐私协议》</Text>
          </Text>
        </View>
      </View>
      <AtToast isOpened={show} text="请阅读并勾选底部协议" onClose={() => setShow(false)}></AtToast>
    </View>
  );
};

export default Index;
